//
//  KLBookDetailController.m
//  KLBookStore
//
//  Created by apple on 2017/10/15.
//  Copyright © 2017年 NetEaseExam. All rights reserved.
//

#import "KLBookDetailController.h"

#import "KLBookTag.h"
#import "KLBookAuthor.h"
#import "KLBookTranslator.h"
#import "KLBookService.h"

#import "UIImageView+WebCache.h"

#import "NSArray+Extension.h"
#import "NSString+Extension.h"

static const CGFloat kNavBgImgHeight = 270.5f;

@interface KLBookDetailController ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIImageView *backgroundImageView;

@end

@implementation KLBookDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self initNavigation];
    [self initSubviews];
}

- (void)initNavigation {
    self.navigationItem.title = @"书籍详情";
}

- (UIImage *)navigationBarBackgroundImage {
    return [UIImage new];
}

- (BOOL)navigationBarShouldShowShadowImage {
    return NO;
}

- (BOOL)shouldHideBottomBarWhenPushed {
    return YES;
}

- (void)initSubviews {
    [self initBackgroundView];
    [self initScrollView];
}

- (void)initBackgroundView {
    self.backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"detail-topbg"]];
    self.backgroundImageView.frame = CGRectMake(0, 0, self.view.frame.size.width, kNavBgImgHeight);
    self.backgroundImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.backgroundImageView];
}

- (void)initScrollView {
    //container
    CGFloat scrollY = [[UIApplication sharedApplication] statusBarFrame].size.height + self.navigationController.navigationBar.frame.size.height;
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, scrollY, self.view.frame.size.width, self.view.frame.size.height-scrollY)];
    scrollView.alwaysBounceVertical = YES;
    scrollView.delegate = self;
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:scrollView];
    
    //header
    UIView *headerView = [[UIView alloc] init];
    headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [scrollView addSubview:headerView];
    
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[headerView(==206.5)]" options:NSLayoutFormatAlignAllCenterX metrics:nil views:NSDictionaryOfVariableBindings(headerView)]];
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[headerView(==scrollView)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(headerView,scrollView)]];
    
    //bookCover
    UIImageView *bookImage = [[UIImageView alloc] init];
    bookImage.translatesAutoresizingMaskIntoConstraints = NO;
    bookImage.backgroundColor = [UIColor whiteColor];
    [bookImage sd_setImageWithURL:[NSURL URLWithString:self.bookEntity.image]];
    [headerView addSubview:bookImage];
    
    [headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-16-[bookImage(115)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bookImage)]];
    [headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-16-[bookImage(161)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bookImage)]];
    
    //title
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.text = self.bookEntity.title;
    titleLabel.font = [UIFont systemFontOfSize:17.0f];
    titleLabel.textColor = [UIColor whiteColor];
    [headerView addSubview:titleLabel];
    
    [headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[bookImage]-14-[titleLabel]-(>=15)-|" options:NSLayoutFormatAlignAllTop metrics:nil views:NSDictionaryOfVariableBindings(bookImage,titleLabel)]];
    
    //detail info
    NSMutableArray *itemsText = [@[] mutableCopy];
    
    if ([self.bookEntity.authors isNotEmptyArray]) {
        NSString *authorList = @"";
        for (KLBookAuthor *author in self.bookEntity.authors) {
            authorList = [[authorList stringByAppendingString:author.name] stringByAppendingString:@" "];
        }
        [itemsText addObject:[NSString stringWithFormat:@"作者：%@",authorList]];
    }
    
    if ([self.bookEntity.translators isNotEmptyArray]) {
        NSString *translatorList = @"";
        for (KLBookTranslator *translator in self.bookEntity.translators) {
            translatorList = [[translatorList stringByAppendingString:translator.name] stringByAppendingString:@" "];
        }
        [itemsText addObject:[NSString stringWithFormat:@"译者：%@",translatorList]];
    }

    if ([self.bookEntity.publisher isNotEmptyString]) {
        [itemsText addObject:[NSString stringWithFormat:@"出版社：%@",self.bookEntity.publisher]];
    }

    if ([self.bookEntity.pubdate isNotEmptyString]) {
        [itemsText addObject:[NSString stringWithFormat:@"出版年份：%@",self.bookEntity.pubdate]];
    }

    if ([self.bookEntity.price isNotEmptyString]) {
        [itemsText addObject:[NSString stringWithFormat:@"定价：%@",self.bookEntity.price]];
    }

    if ([self.bookEntity.isbn13 isNotEmptyString]) {
        [itemsText addObject:[NSString stringWithFormat:@"ISBN：%@",self.bookEntity.isbn13]];
    } else if ([self.bookEntity.isbn10 isNotEmptyString]) {
        [itemsText addObject:[NSString stringWithFormat:@"ISBN：%@",self.bookEntity.isbn10]];
    }
    
    __block UILabel *lastLabel = titleLabel;
    
    [itemsText enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UILabel *itemLabel = [[UILabel alloc] init];
        itemLabel.translatesAutoresizingMaskIntoConstraints = NO;
        itemLabel.text = obj;
        itemLabel.font = [UIFont systemFontOfSize:11.0f];
        itemLabel.textColor = [UIColor whiteColor];
        [headerView addSubview:itemLabel];
        
        [headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[bookImage]-14-[itemLabel]-(>=15)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bookImage,itemLabel)]];
        [headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lastLabel]-4-[itemLabel]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(lastLabel,itemLabel)]];
        //lastLabel为前面所有label的合体，这样不断往上叠加label
        lastLabel = itemLabel;
    }];
    
    //fav Btn
    UIButton *favBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    favBtn.translatesAutoresizingMaskIntoConstraints = NO;
    favBtn.titleLabel.font = [UIFont systemFontOfSize:12.0f];
    [favBtn setBackgroundColor:[UIColor whiteColor]];
    [favBtn setTitle:@"收藏" forState:UIControlStateNormal];
    [favBtn setTitle:@"已收藏" forState:UIControlStateDisabled];
    [favBtn setTitleColor:UIColorFromHexRGB(0x00A25B) forState:UIControlStateNormal];
    [favBtn setTitleColor:UIColorFromHexRGB(0xB8B8B8) forState:UIControlStateDisabled];
    //判断是否已经收藏
    KLBookEntity *book = [KLBookService searchFavoredBookWithDoubanId:_bookEntity.doubanId];
    if (book!=nil) {
        favBtn.enabled = NO;
    }
    
    favBtn.layer.cornerRadius = 2.0f;
    [favBtn addTarget:self action:@selector(didClickFavorButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [headerView addSubview:favBtn];
    
    [headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[bookImage]-14-[favBtn(==70)]" options:NSLayoutFormatAlignAllBottom metrics:nil  views:NSDictionaryOfVariableBindings(bookImage,favBtn)]];
    
    [headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[favBtn(==27)]" options:0 metrics:nil  views:NSDictionaryOfVariableBindings(favBtn)]];
    
    //body
    UIView *bodyView = [[UIView alloc] init];
    bodyView.translatesAutoresizingMaskIntoConstraints = NO;
    bodyView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:bodyView];
    
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[bodyView(==scrollView)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bodyView,scrollView)]];
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[headerView]-0-[bodyView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(headerView,scrollView,bodyView)]];
    
    //summary
    UILabel *summaryLabel = [[UILabel alloc] init];
    summaryLabel.text = @"内容简介";
    summaryLabel.font = [UIFont systemFontOfSize:16.0f];
    summaryLabel.textColor = UIColorFromHexRGB(0x555555);
    summaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [bodyView addSubview:summaryLabel];
    
    //summary deatail
    UILabel *detailLabel = [[UILabel alloc] init];
    detailLabel.numberOfLines = 0;
    detailLabel.text = self.bookEntity.summary;
    detailLabel.font = [UIFont systemFontOfSize:15.0];
    detailLabel.textColor = UIColorFromHexRGB(0x999999);
    detailLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [bodyView addSubview:detailLabel];
    
    [bodyView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-15-[summaryLabel]-6.5-[detailLabel]-15-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(summaryLabel,detailLabel)]];
    [bodyView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[summaryLabel]-15-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(summaryLabel)]];
    [bodyView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[detailLabel]-15-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(detailLabel)]];
}

#pragma mark - actions
- (void)didClickFavorButton:(UIButton *)button {
    
    long long bookId = [KLBookService favorBook:self.bookEntity];
    if (bookId > 0) {
        button.enabled = NO;
        NSNotification *notification =[NSNotification notificationWithName:@"FavorBookNotification" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }
}

#pragma mark - scroll action

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        //向下滚动改变背景图尺寸
        self.backgroundImageView.frame = CGRectMake(0, 0, self.view.frame.size.width, kNavBgImgHeight - scrollView.contentOffset.y);
    } else {
        //其他情况重置背景图尺寸
        self.backgroundImageView.frame = CGRectMake(0, 0, self.view.frame.size.width, kNavBgImgHeight);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
